import time
from selenium.webdriver.common.by import By
from taobao_check.tools import click_by_js
from .base import BaseBrush


class YunYing(BaseBrush):
    login_url = "http://180.188.18.184:8866/business.php/user/login.html"
    index_url = "http://180.188.18.184:8866/business.php/msg/getlist.html"
    check_url = "http://180.188.18.184:8866/business.php/Selfaudit/index/"

    def __init__(self, config, tab):
        super().__init__("韵营", "yunying", config, tab)
        self.count = 0

    def login(self):
        if self.browser.current_url != self.login_url:
            self.browser.get(self.login_url)

        self.enter_text((By.ID, "phone"), self.username)
        self.enter_text((By.ID, "password"), self.password)
        self.click_button((By.CSS_SELECTOR, "a.btn_bdsj"))

        while self.browser.current_url != self.index_url:
            time.sleep(0.1)

        self.browser.get(self.check_url)

    def check_user(self):
        try:
            trs = self.find_elements((By.CSS_SELECTOR, "tbody>tr"), timeout=8)
        except Exception as e:
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            self.count += 1
            if self.count == 100:
                self.print_log("count=100", debug=True)
                self.count = 0
                self.browser.get(self.index_url)
                self.sleep(5)
            return False
        flag = False
        for tr in trs:
            tds = tr.find_elements_by_tag_name("td")
            if len(tds) < 9:
                continue

            username = tds[-2].get_attribute('textContent').strip()
            username = username.split("\n")[0].strip()
            self.print_log(f"当前待验买号为：【{username}】")

            start = time.time()
            result = self.check.check_user(username, self.print_log)
            self.print_log(f"验号结果为: {'通过' if result else '不通过'}. 用时: {time.time() - start:.2f}s")

            # 点击审核按钮
            check_button = tds[-1].find_element_by_tag_name("a")
            click_by_js(self.browser, check_button)
            # div = self.find_element((By.CSS_SELECTOR, "div.layui-layer"))
            # 选择审核不通过
            if not result:
                option = self.find_element((By.CSS_SELECTOR, "div.layui-layer input"))
                click_by_js(self.browser, option)
                dd = self.find_elements((By.CSS_SELECTOR, "div.layui-layer dd"))[-1]
                click_by_js(self.browser, dd)
            # 点击确认
            self.click_button((By.CSS_SELECTOR, "a.layui-layer-btn0"))
            flag = True
            break

        if not flag:
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            return False
        else:
            self.sleep(2)
            return True
